/**
 * Copyright (c) Huawei Technologies Co., Ltd. 1987-2021. All rights reserved.
*/

package com.gitee.fufu669.config.exception;

import com.fasterxml.jackson.annotation.JsonProperty;

import lombok.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/** @author wangfupeng */
@Data
// 注解
@Builder
// 注解
@NoArgsConstructor
// 注解
@AllArgsConstructor
// 注解
@EqualsAndHashCode(callSuper = false)
/**
 * TODO
*/
public class CacheServerException extends RuntimeException {

    // 赋值
    private static final long serialVersionUID = 3687466179508097339L;

    // 日志对象
    private static final Logger logger = LoggerFactory.getLogger(CacheServerExceptionHandler.class);

    // TODO
    private String code;
    // TODO
    private String message;
    // TODO
    private Object data;

    // 创建
    private static Map<String, String> props = new ConcurrentHashMap<>();

    // 静态代码块
    static {
        // TODO
        Arrays.stream(CacheServerErrorCode.class.getDeclaredFields())
                // 遍历
                .forEach(p -> {
                    // 尝试下面的代码
                    try {
                        // TODO
                        CacheErrorMessage annotation = p.getAnnotation(CacheErrorMessage.class);
                        // 塞入
                        props.put(String.valueOf(p.get("value")), annotation.value());
                    // 捕捉异常
                    } catch (Exception e) {
                        logger.info("fail to load error code:  " + p.getName());
                    }
                });
    }

    /**
     * TODO
    */
    public CacheServerException(String code, Object... msg) {
        // 字符串赋值
        String message = props.get(String.valueOf(code));
        // 判断是否非空
        if (msg != null && msg.length > 0) {
            // TODO
            message = MessageFormat.format(message, msg);
        }
        // 赋值
        this.code = code;
        // 赋值
        this.message = message;
    }
}
